package form;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

abstract public class FormContainer extends FormNode
{
	protected ArrayList<FormNode> children = new ArrayList<FormNode>();
	
	public void addChild(FormNode child)
	{
		children.add(child);
	}
	
	public void removeChild(FormNode child)
	{
		children.remove(child);
	}
	
	public void setChildren(List<FormNode> children)
	{
		this.children = new ArrayList<FormNode>(children);
	}
	
	public List<FormNode> getChildren()
	{
		return children;
	}
	
	public void removeChildren()
	{
		children.clear();
	}
	
	public String getChildrenCode()
	{
		String code = "";
		
		for (FormNode child: children)
		{
			code += child;
		}
		
		return code;
	}
	
	public List<FormField> getFields()
	{
		List<FormField> fields = new ArrayList<FormField>();
		
		for (FormNode child: children)
		{
			if (child instanceof FormField)
			{
				fields.add((FormField) child);
			}
		}
		
		return fields;
	}
	
	public List<String> getFieldNames()
	{
		ArrayList<String> fields = new ArrayList<String>();
		
		for (FormField field: getFields())
		{
			fields.add(field.getName());
		}
		
		return fields;
	}
	
	public void populate(Map<String, Object> values)
	{
		for (FormNode child: children)
		{
			if (child instanceof FormContainer)
			{
				((FormContainer) child).populate(values);
			}
			else if (child instanceof FormField)
			{
				FormField field = (FormField) child;
				
				field.setValue(values.get(field.getName()));
			}
		}
	}
	
	public Map<String, Object> getValues()
	{
		Map<String, Object> values = new HashMap<String, Object>();
		
		for (FormNode child: children)
		{
			if (child instanceof FormContainer)
			{
				values.putAll(((FormContainer) child).getValues());
			}
			else if (child instanceof FormField)
			{
				FormField element = (FormField) child;
				
				values.put(element.getName(), element.getValue());
			}
		}
		
		return values;
	}

	public void clear()
	{
		for (FormNode child: children)
		{
			if (child instanceof FormContainer)
			{
				((FormContainer) child).clear();
			}
			else if (child instanceof FormField)
			{
				((FormField) child).clear();
			}
		}
	}
	
	public boolean isValid()
	{
		boolean valid = true;
		
		for (FormField field: getFields())
		{
			if (!field.isValid())
			{
				// No break, because we want to check all children so errors are added.
				valid = false;
			}
		}
		
		return valid;
	}
	
	@Override
	public boolean isShortTag()
	{
		return false;
	}
	
	@Override
	public String getCode()
	{
		return ('<' + getTagName() + getAttributesCode() + '>' + getChildrenCode() + "</" + getTagName() + '>'); 
	}
}
